__author__ = 'kying'


class treeNode:
    def __init__(self,namevalue,numOccur,parentNode):
        self.name=namevalue
        self.count=numOccur
        self.nodeLink=None
        self.parent=parentNode
        self.children={}

    def inc(self,numOccur):
        self.count+=numOccur

    def disp(self,ind=1):
        print ' '*ind,self.name,' ',self.count
        for child in self.children.values():
            child.disp(ind+1)


rootNode=treeNode('pyramid',9,None)

rootNode.children['eye']=treeNode('eye',13,None)
rootNode.children['phoenix']=treeNode('phoenix',3,None)

rootNode.disp()

def createTree(dataSet,minSup=1):
    headerTable={}
    for trains in dataSet:
        for item in trains:
            headerTable[item]=headerTable.get(item,0)+dataSet[trains]
    for k in headerTable.keys():
        if headerTable[k]<minSup:
            del(headerTable[k])
    freqItemSet=set(headerTable.keys())
    if len(freqItemSet)==0:
        return None,None
    for k in headerTable:
        headerTable[k]=[headerTable[k],None]

    retTree=treeNode('NUll Set',1,None)

    for tranSet,count in dataSet.items():
        localD={}
        for item in tranSet:
            if item in freqItemSet:
                localD[item]=headerTable[item][0]
            if len(localD)>0:
                orderedItems=[v[0] for v in sorted(localD.items(),key=lambda p:p[1],reverse=True)]
                updateTree(orderedItems,retTree,headerTable,count)
    return retTree,headerTable

def updateTree(items,inTree,headerTable,count):
    if items[0] in inTree.children:
        inTree.children[items[0]].inc(count)
    else:
        inTree.children[items[0]]=treeNode(items[0],count,inTree)
        if headerTable[items[0]][1]==None:
            headerTable[items[0]][1]=inTree.children[items[0]]



Filename="F:\\DataSets\\CVS1.txt"

def Dataset():
    text=open(Filename,'r').readlines()
    Data={}
    for line in text:
        line=line.strip().split(",")
        Data[frozenset(line)]=1

    return Data

Item=Dataset()

myHeadTree,myHead=createTree(Item,3)

myHeadTree.disp()













